<template>
  <div class="edit-patient-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="编辑就诊人" left-arrow @click-left="goBack">
      <template #right>
        <van-icon name="ellipsis" size="18" />
        <van-icon name="ellipsis" size="18" style="margin-left: 16px;" />
      </template>
    </van-nav-bar>

    <!-- 加载状态 -->
    <van-loading v-if="loading" class="loading" />

    <!-- 表单内容 -->
    <div v-else class="form-content">
      <p class="instruction">请认真填写就诊人信息</p>

      <van-form @submit="handleSubmit" ref="formRef">
        <van-cell-group inset>
          <!-- 关系选择 -->
          <van-field
            v-model="form.relationship"
            name="relationship"
            label="关系"
            placeholder="请选择与本人关系"
            readonly
            is-link
            @click="showRelationshipPicker = true"
            :rules="[{ required: true, message: '请选择关系' }]"
          />

          <!-- 姓名 -->
          <van-field
            v-model="form.name"
            name="name"
            label="姓名"
            placeholder="请输入真实姓名"
            :rules="[{ required: true, message: '请输入姓名' }]"
          />

          <!-- 证件类型选择 -->
          <van-field
            v-model="form.idCardType"
            name="idCardType"
            label="证件类型"
            placeholder="请选择证件类型"
            readonly
            is-link
            @click="showIdCardTypePicker = true"
            :rules="[{ required: true, message: '请选择证件类型' }]"
          />

          <!-- 证件号码 -->
          <van-field
            v-model="form.idCardNum"
            name="idCardNum"
            label="证件号码"
            placeholder="输入证件号码"
            :rules="[{ required: true, message: '请输入证件号码' }]"
          />

          <!-- 就诊卡号 -->
          <van-field
            v-model="form.medicalCard"
            name="medicalCard"
            label="就诊卡号"
            placeholder="请输入就诊卡号"
            :rules="[{ required: true, message: '请输入就诊卡号' }]"
          />

          <!-- 手机号码 -->
          <van-field
            v-model="form.phone"
            name="phone"
            label="手机号码"
            placeholder="请输入手机号码"
            type="tel"
            :rules="[
              { required: true, message: '请输入手机号码' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
            ]"
          />

          <!-- 地址 -->
          <van-field
            v-model="form.address"
            name="address"
            label="就诊人地址"
            placeholder="选填"
            type="textarea"
            rows="2"
            autosize
          />
        </van-cell-group>

        <!-- 设为默认就诊人 -->
        <div class="default-toggle">
          <span class="toggle-label">设为默认就诊人</span>
          <van-switch v-model="form.isDefault" />
        </div>

        <!-- 提示信息 -->
        <div class="info-text">
          <p>初次添加就诊人请绑定本院就诊卡号,未持有本院就诊卡的患者需到本院自助机或窗口办理就诊卡后方可进行添加。</p>
        </div>

        <!-- 操作按钮 -->
        <div class="button-container">
          <van-button
            type="primary"
            size="large"
            block
            round
            native-type="submit"
            :loading="isSubmitting"
            class="save-button"
          >
            {{ isSubmitting ? '保存中...' : '保存' }}
          </van-button>
          
          <van-button
            type="danger"
            size="large"
            block
            round
            @click="handleDelete"
            :loading="isDeleting"
            class="delete-button"
          >
            {{ isDeleting ? '删除中...' : '删除就诊人' }}
          </van-button>
        </div>
      </van-form>
    </div>

    <!-- 关系选择器 -->
    <van-popup v-model:show="showRelationshipPicker" position="bottom">
      <van-picker
        :columns="relationshipOptions"
        @confirm="onRelationshipConfirm"
        @cancel="showRelationshipPicker = false"
      />
    </van-popup>

    <!-- 证件类型选择器 -->
    <van-popup v-model:show="showIdCardTypePicker" position="bottom">
      <van-picker
        :columns="idCardTypeOptions"
        @confirm="onIdCardTypeConfirm"
        @cancel="showIdCardTypePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Toast, Dialog } from 'vant'
import { api, type PatientForm, type Patient } from '@/api'

const router = useRouter()
const route = useRoute()
const formRef = ref()

// 获取就诊人ID
const patientId = parseInt(route.params.id as string)

// 表单数据
const form = reactive<PatientForm>({
  relationship: '',
  name: '',
  idCardType: '',
  idCardNum: '',
  medicalCard: '',
  phone: '',
  address: '',
  isDefault: false
})

// 状态
const loading = ref(true)
const isSubmitting = ref(false)
const isDeleting = ref(false)
const showRelationshipPicker = ref(false)
const showIdCardTypePicker = ref(false)

// 选项数据
const relationshipOptions = [
 '本人',
  '父母', 
  '配偶',
  '子女',
  '兄弟',
  '姐妹',
  '其他'
]

const idCardTypeOptions = [
  '身份证',
  '护照',
  '军官证',
  '其他'
]

// 事件处理
const goBack = () => {
  router.back()
}

const onRelationshipConfirm = (value: any) => {
  console.log('关系选择器确认事件:', value)
  if (typeof value === 'string') {
    form.relationship = value
  } else if (value && value.selectedValues) {
    form.relationship = value.selectedValues[0]
  } else if (value && value.selectedOptions) {
    form.relationship = value.selectedOptions[0].value
  }
  showRelationshipPicker.value = false
  console.log('设置关系为:', form.relationship)
}

const onIdCardTypeConfirm = (value: any) => {
  console.log('证件类型选择器确认事件:', value)
  if (typeof value === 'string') {
    form.idCardType = value
  } else if (value && value.selectedValues) {
    form.idCardType = value.selectedValues[0]
  } else if (value && value.selectedOptions) {
    form.idCardType = value.selectedOptions[0].value
  }
  showIdCardTypePicker.value = false
  console.log('设置证件类型为:', form.idCardType)
}

// 加载就诊人信息
const loadPatientInfo = async () => {
  try {
    const response = await api.getPatientById(patientId)
    const patient = response.data
    
    // 填充表单数据
    form.relationship = patient.relationship
    form.name = patient.name
    form.idCardType = patient.idCardType
    form.idCardNum = patient.idCardNum
    form.medicalCard = patient.medicalCard
    form.phone = patient.phone
    form.address = patient.address
    form.isDefault = patient.isDefault
  } catch (error) {
    console.error('获取就诊人信息失败:', error)
    Toast('获取就诊人信息失败')
    router.back()
  } finally {
    loading.value = false
  }
}

const handleSubmit = async () => {
  if (isSubmitting.value) return

  isSubmitting.value = true
  try {
    await api.updatePatient(patientId, form)
    Toast('保存成功')
    router.back()
  } catch (error) {
    console.error('更新就诊人失败:', error)
    Toast('保存失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

const handleDelete = async () => {
  try {
    await Dialog.confirm({
      title: '确认删除',
      message: `确定要删除就诊人"${form.name}"吗？`,
    })
    
    isDeleting.value = true
    await api.deletePatient(patientId)
    Toast('删除成功')
    router.back()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除就诊人失败:', error)
      Toast('删除失败')
    }
  } finally {
    isDeleting.value = false
  }
}

onMounted(() => {
  loadPatientInfo()
})
</script>

<style scoped>
.edit-patient-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.form-content {
  padding: 16px;
}

.instruction {
  color: #969799;
  font-size: 14px;
  margin: 0 0 16px 0;
  text-align: center;
}

.default-toggle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: white;
  margin: 16px 0;
  border-radius: 8px;
}

.toggle-label {
  font-size: 16px;
  color: #323233;
}

.info-text {
  margin: 16px 0;
  padding: 16px;
  background: #f7f8fa;
  border-radius: 8px;
}

.info-text p {
  color: #969799;
  font-size: 12px;
  line-height: 1.5;
  margin: 0;
}

.button-container {
  margin-top: 32px;
  padding: 0 16px;
}

.save-button {
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #1989fa 0%, #1976d2 100%);
  border: none;
  margin-bottom: 16px;
}

.save-button:active {
  opacity: 0.8;
}

.delete-button {
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
  border: none;
}

.delete-button:active {
  opacity: 0.8;
}

/* 表单样式调整 */
:deep(.van-cell-group) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.van-field__label) {
  color: #323233;
  font-weight: 500;
}

:deep(.van-field__control) {
  color: #323233;
}

:deep(.van-field__control::placeholder) {
  color: #c8c9cc;
}

/* 选择器样式 */
:deep(.van-picker) {
  background: white;
}

:deep(.van-picker__toolbar) {
  background: white;
  border-bottom: 1px solid #ebedf0;
}
</style>
